package safety

import (
	"math/rand"
	"strings"
	"time"
)

const (
	lowerCharSet   = "abcdedfghijklmnopqrst"
	upperCharSet   = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
	specialCharSet = "!@#&*"
	numberSet      = "0123456789"
	allCharSet     = lowerCharSet + upperCharSet + specialCharSet + numberSet
)

// 密码长度，最小特殊字符、数字、小写字母、大写字母的长度
func generatePassword(passwordLength, minSpecialChar, minNum, minLowerCase, minUpperCase int) string {
	seed := time.Now().UnixNano()
	rng := rand.New(rand.NewSource(seed))
	var password strings.Builder
	//Set special character
	for i := 0; i < minSpecialChar; i++ {
		random := rng.Intn(len(specialCharSet))
		password.WriteString(string(specialCharSet[random]))
	}

	//Set numeric
	for i := 0; i < minNum; i++ {
		random := rng.Intn(len(numberSet))
		password.WriteString(string(numberSet[random]))
	}

	//Set uppercase
	for i := 0; i < minUpperCase; i++ {
		random := rng.Intn(len(upperCharSet))
		password.WriteString(string(upperCharSet[random]))
	}

	//Set lowercase
	for i := 0; i < minLowerCase; i++ {
		random := rng.Intn(len(lowerCharSet))
		password.WriteString(string(lowerCharSet[random]))
	}

	remainingLength := passwordLength - minSpecialChar - minNum - minUpperCase
	for i := 0; i < remainingLength; i++ {
		random := rng.Intn(len(allCharSet))
		password.WriteString(string(allCharSet[random]))
	}
	// 转化为 utf8 格式的数组，将数组随机打乱
	inRune := []rune(password.String())
	rng.Shuffle(len(inRune), func(i, j int) {
		inRune[i], inRune[j] = inRune[j], inRune[i]
	})
	return string(inRune)
}

func GenPasswd() (pwd string) {
	minSpecialChar := 1
	minNum := 1
	minLowerCase := 1
	minUpperCase := 1
	passwordLength := 8
	return generatePassword(passwordLength, minSpecialChar, minNum, minLowerCase, minUpperCase)
}
